package org.example.jwt1.handler;
import com.fasterxml.jackson.databind.ObjectMapper;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.jwt1.entity.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;

/* 当未登录或者token失效访问接口时，自定义的返回结果
 */
@Component
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {

    //Jackson提供的JSON转换类ObjectMapper,可以用Spring自动注入
    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        ResponseResult sr = new ResponseResult();
        sr.setFlag(false);
        sr.setCode(2);
        sr.setErrorMsg("尚未登录，或者登录过期");
        //转换成JSON
        String s = objectMapper.writeValueAsString(sr);
        //响应给浏览器
        response.getWriter().write(s);
    }
}
